<?php
/**                                          
 * 微博
 * @author M2
 * @version 1.0
 * create Date 2013-04-27
 */
class WeiboModel extends Model{
    /**
	 * 微博发布
	 * @param $uid 发布者用户ID
	 * @param $data 微博主要数据
	 * @param $from 从哪发布的
	 * @param $type 微博类型
	 * @param $type_data 微博类型传来的数据
	 * @return return_type
	 */
     function publish($uid, $data, $from=0, $type=0, $type_data, $sync, $from_data){
     	$data['content'] = $data['content'];
     	if($id = $this->doSaveWeibo($uid, $data, $from , $type ,$type_data, $from_data)){
     		if(($num = S("userInfo_miniNum_".$uid)) !== false){
     			$num = intval(S("userInfo_miniNum_".$uid)) + 1;
     			S("userInfo_miniNum_".$uid,$num);
     		}
     		$this->notifyToAtme($uid, $id, $data['content'] );
     		$weiboimageConfig = include SITE_PATH . '/apps/weibo/Conf/weiboimageConfig.php';
     		if($from === 0 && $weiboimageConfig['opennosql'] === "1"){
     			include_once( "./apps/weibo/Lib/Action/MessageAction.class.php" );
     			$msgdata = array('messageid'=>intval($id),'userid'=>$uid.'','username'=>common("String")->getUserName($uid));
     			$msga = new MessageAction();
     			$res = $msga -> add($msgdata);
     			if(!$res){
     				$this->deleteMini($id);
     				return false;
     			}
     		}
     		return $id;
     	}else{
     		return false;
     	}     	
    }
    
	/**
	 * 删除一条微博	
	 * @param int $id 微博ID
	 * @param int $uid 用户ID
	 */
    function deleteMini($id,$uid){
		if($GLOBALS['yl']['isSystemAdmin']){
			$where = "weibo_id=$id";
		}else{
			$where = "weibo_id=$id AND uid=$uid";
		}
    	if( $info = $this->where($where)->find()){
    		$data['weibo_id'] = $info['weibo_id'];
            if ($this->where($data)->setField('isdel',1)){
	    		//关联操作
	    		if( $info['transpond_id'] ){
	    			$this->where('weibo_id='.$info['transpond_id'])->setDec('transpond');
	    		}
	    		//删除mongodb上和up云上的数据
	    		$this->deleteUpyunAndMongoMsg($data['weibo_id']);
	    		
	    		//同时删除@用户的微博数据
                model('Atme')->where($data)->delete();
	    		//同时删除收藏
                model('Favorite')->where($data)->delete();
	    		//同时删除评论
                model('Comment')->where($data)->setField('isdel',1);
                $this->_removeWeiboCache($id);
				//同时更新话题微博数
				model('Topic')->deleteWeiboJoinTopic($info['content'], $info['weibo_id']);
                //同时彻底删除评论
//                 model('Comment')->where($data)->delete();
			    //修改登录用户缓存信息--修改微博数目
			    $userLoginInfo = S('S_userInfo_'.$uid);
			    if(!empty($userLoginInfo)) {
			    	$userLoginInfo['miniNum'] = strval($userLoginInfo['miniNum'] - 1);
			    	S('S_userInfo_'.$uid, $userLoginInfo);
			    }
            }else{
    			return false;
    		}
            return true;
    	}else{
    		return false;
    	}
    }
    
    /**
     * 删除微博对应的mongodb数据和 upyun数据
     * @param  $messageid
     */
    function deleteUpyunAndMongoMsg($messageid){
     	include_once( "./apps/weibo/Lib/Action/MessageAction.class.php" );
      	$msga = new MessageAction();
      	//删除mongodb上的 message信息
     	$msga ->deleteMessage($messageid);
     	include_once( "./apps/weibo/Lib/Action/PictureAction.class.php" );
      	$pica = new PictureAction();
      	//从mongodb上取出图片列表
      	$pics= unserialize($pica->getPics($messageid));
      	if(!empty($pics['picurl'])){
      		$pics[0]['picurl'] = $pics['picurl'];
      		unset($pics['picurl']);
      	}
      	if($pics){
     	    $yunConfig = include SITE_PATH . '/apps/admin/Conf/yun.php';
     	    if (intval ( $yunConfig ['openyun'] )) {
      	    	  	import ( "ORG.Upyun.upyun" );
      	    	  	if (empty ( $yunConfig ['picbucket'] ) || empty ( $yunConfig ['yunname'] ) || empty ( $yunConfig ['yunpass'] )) {
      	    	  		//$this->error ( "没有配置" );
      	    	  		//exit ();
      	    	  		return false;
      	    	  	}
     	    	  	$upyun = new UpYun ( $yunConfig ['picbucket'], $yunConfig ['yunname'], $yunConfig ['yunpass'] );
     	    	  	foreach($pics as $picurl){
     	    	  		//去掉字符串的｛upyun｝
     	    	  		$picurl_temp = str_replace("{upyun}",'',$picurl['picurl']);
     	    	  	 	$upyun->deleteFile($picurl_temp);
     	    	  	}
     	    }   
    	     $pica->delete($messageid); 
    	  } 
    }
    
	/**
	 * 发布微博	
	 * @param int $uid 用户ID
	 * @param array $data
	 * @param int $from 来自
	 * @param int $type 类型
	 * @param object $type_data
	 * @param string $from_data 微博数据
	 */
    function doSaveWeibo($uid, $data, $from=0, $type=0, $type_data=null, $from_data=null){
		//用户不存在时无法发微博、把用户退出处理
		$result = model('User')->find($uid);
		if(!$result){
			return false;
		}
        $save['uid']			= $uid;
        $save['transpond_id']	= intval( $data['transpond_id'] );
        $save['for_weibo_id']	= intval( $data['for_weibo_id'] );
        $save['from']			= intval( $from );  //0网站 1手机网页版 2 android 3 iphone
        $save['transpond']      = 0;
        $save['isdel']          = 0;
        $save['comment']        = 0;
		$save['pub_ip']	 = get_client_ip();
		$save['ctime']      = time();
		$save['from_data']		= $from_data;	
		$save['content'] = $data['content'];
	    // 微博类型钩子
	    if($type === 1){
	    	$addonsData = array();
	    	include_once( "./Plugins/WeiboImage/WeiboImageActions.class.php" );
	    	$im = new WeiboImageActions();			
			$im->weibo_type(array('typeId'=>$type,'typeData'=>$type_data,'result'=>&$addonsData));
			$save = array_merge($save,$addonsData);
			$weiboimageConfig = include SITE_PATH . '/apps/weibo/Conf/weiboimageConfig.php';
			if($weiboimageConfig['opennosql'] === "1"){
				$imagedata = empty($addonsData['type_data']) ?null:unserialize($addonsData['type_data']);
				unset($save['type_data']);
			}
        } elseif($type === 3) {
        	$addonsData = array();
        	include_once( "./Plugins/WeiboVideo/WeiboVideoActions.class.php" );
        	$vi = new WeiboVideoActions();
        	$vi->weibo_type(array('typeId'=>$type,'typeData'=>$type_data,'result'=>&$addonsData));
        	$save = array_merge($save,$addonsData);
        } elseif($type ===4) {
        	$addonsData = array();
        	include_once( "./Plugins/WeiboMusic/WeiboMusicActions.class.php" );
        	$vi = new WeiboMusicActions();
        	$vi->weibo_type(array('typeId'=>$type,'typeData'=>$type_data,'result'=>&$addonsData));
        	$save = array_merge($save,$addonsData);
        } elseif($data['type']){
			$save['type'] = intval( $data['type'] );
			$save['type_data'] = $data['type_data'];
		}
		//写入数据库
        if( $id = $this->add( $save ) ){
        	//保存一份数据到mongodb
        	if(!empty($imagedata)){
        		if(empty($imagedata[0])){
        			$temp = $imagedata;
        			unset($imagedata);
        			$imagedata[0] = $temp;
        		}
        		$picdata = array("messageid" => $id,
        				"userid" => $uid,
        				"uname" => $result['uname'],
        				"data" => $imagedata);
        		include_once( "./apps/weibo/Lib/Action/PictureAction.class.php" );
        		$pica = new PictureAction();
        		$pica -> add($picdata);
        	}
        	if( $save['transpond_id']){
        		$this->where('weibo_id='.$save['transpond_id'])->setInc('transpond');
        		$this->where('weibo_id='.$save['for_weibo_id'])->setInc('transpond');
        	}
        	$save['weibo_id'] = $id;
        	$this->_setWeiboCache($id, $save);
		    //修改登录用户缓存信息--添加微博数目
		    $userLoginInfo = S('S_userInfo_'.$uid);
		    if(!empty($userLoginInfo)) {
		    	$userLoginInfo['miniNum'] = strval($userLoginInfo['miniNum'] + 1);
		    	S('S_userInfo_'.$uid, $userLoginInfo);
		    }
        	$weiboInfoWithLink['type'] = $save['type'];
        	$weiboInfoWithLink['transpond_id'] = $save['transpond_id'];
        	model('Topic')->addTopic( html_entity_decode($save['content'],ENT_QUOTES), $id, $weiboInfoWithLink);
        	if($type && $save['type']){
        		PluginManager::trigger('weibo_type_publish',array('weiboId'=>$id,'type'=>$type,'typeData'=>$type_data, 'data'=>$save));
        	}
        	return $id;
        }else{
        	return false;
        }
    }
    
    /**
     * 微博详细	
     * @param int|array $id 微博ID
     */
    public function getWeiboDetail($id){
        if(is_array($id)){
			$id = array_unique(array_filter($id));
            $res = array();
            $no_cache = array();
            foreach($id as $value){
                $detail = $this->_getWeiboCache($value);
                if(empty($detail) || !$detail){
                   $no_cache[] = $value;
                   $res[$value] = false;
                }else{
                    if(!$detail['isdel']){
                        $res[]  = $detail;
                    }
                }
            }
            $no_cache = array_unique(array_filter($no_cache));
            if(!empty($no_cache)){
                $map['weibo_id'] = array('in',$no_cache); 
                $noCacheWeiboInDb = $this->where($map)->select();
                foreach($noCacheWeiboInDb as $value){
                    if(!$value['isdel']){
                        $res[$value['weibo_id']] = $value;
                    }
                }
                $this->setWeiboObjectCache($noCacheWeiboInDb);
            }
        }else{
            $res = $this->_getWeiboCache($id);
            if(empty($res)||!$res){
                $res = $this->where('weibo_id='.$id.' and isdel=0')->find();
                $this->_setWeiboCache($id, $res);
            }
            if($res['isdel']) return false;
        }
        return $res;
    }
    
	/**
	 * 转发操作	
	 * @param int $uid 用户ID
	 * @param array $data
	 * @param boolean $api
	 */
    function transpond($uid,$data,$api=false){
		$post['content']       = common('Html')->text( $data['content'] );
	    $post['transpond_id']  = intval( $data['transpond_id'] );
	    $post['for_weibo_id']  = intval( $data['for_weibo_id'] );
	    F('weibo_detail_'.$post['transpond_id'],NULL,'./runtime/home/data/');
	    $transponInfo = $this->field('weibo_id,uid,content,type')->where('weibo_id='.$post['transpond_id'].' AND isdel=0')->find();
	    $post['type'] = $transponInfo['type'];
        if( $data['reply_weibo_id'] ){ //对相应微博ID作出评论
        	foreach ( $data['reply_weibo_id'] as $value ){
				if($value == 0) continue;
				$weiboinfo = $this->field('uid')->where('weibo_id='.$value.' AND isdel=0')->find();
	        	$comment['uid']       = $uid;
	        	$comment['reply_uid'] = $weiboinfo['uid'];
	        	$comment['weibo_id']  = $value;
	        	$comment['content']   = $post['content'];
	        	$comment['ctime']     = time();
	        	$commentid = model('Comment')->addcomment( $comment );
	        	model('UserCount')->addCount($weiboinfo['uid'],'comment');
        	}
        }
	    $id = $this ->doSaveWeibo( $uid , $post , intval($data['from']) );
	    if($id){
	    	$this->notifyToAtme($uid,$id, $post['content'], $transponInfo['uid']);
	    	
	    	return $data['imagemutiple']?$commentid:$id;
	    }else{
	    	return false;
	    }
    }
        
	/**
	 * 获取未取出来的新微博条数	
	 * @param int $uid 用户ID
	 * @param int $lastId 最后一条的ID
	 * @param int|string $type
	 * @param int $follow_gid 分组ID
	 */
	function loadMore($uid,$lastId,$type=null,$follow_gid=null){
	    return $this->__optToNew( $uid,$lastId,$type,$follow_gid,20,true );
	}
	
	/**
	 * 获取未取出来的新微博条数
	 * @param int $uid 用户ID
	 * @param int $lastId 最后一条的ID
	 * @param int|string $type
	 * @param int $follow_gid 分组ID
	 * @param int $limit 显示条数
	 */
	private function __optToNew($uid,$lastId,$type='index',$follow_gid=null,$limit = 0,$since = false){
		if(!empty($type) && $type >0){
	        $type_str = " and type=".intval($type);
		}
		if($type==='original'){
			$type_str = " and transpond_id=0";
	    }
		if($since){
	        if($lastId >0){
	            $weiboId = "weibo_id<{$lastId} and";
	        }
	    }else{
	        if($lastId >0){
	            $weiboId = "weibo_id>{$lastId} and";
	        }
	    }
	    $map="{$weiboId} isdel=0 {$type_str}";
		if($uid>0){
			$followCount = model('Follow')->getUserFollowCount($uid);
			if($followCount){
				if(!empty($follow_gid)){
					$fids = model('FollowGroup')->getUsersByGroup($uid,$follow_gid);
					$map.=' AND uid IN ('.implode(',',$fids).')';
				}else{
					$map.=" AND ( uid IN (SELECT fid FROM {$this->tablePrefix}weibo_follow WHERE uid=$uid AND type=0) OR uid={$uid} )";
				}
			}else{//无关注时.数据为空.
				$map.=' AND uid = '.$uid;
			}
		}
	    if($limit){
	        $list = $this->field('weibo_id')->where($map)->order('weibo_id DESC')->limit($limit)->select();
			unset($map);
	        //取出微博的实际数据
	        $weibo_id_list = common('Array')->getSubByKey($list,'weibo_id');
	        $data= $this->getWeiboDetail($weibo_id_list);

	        $result = array();
	        foreach( $data as $key=>$value){
	            $result[] = $this->getOne($value['weibo_id'],$value);
	        }
	        $list['data'] = $result;
	    }else{
			$list = $this->where($map)->count();
	    }
	    return $list;
	}
    
    /**
     * 给提到我的发通知 	
     * @param int $uid 用户ID
     * @param int $id 微博ID
     * @param int $transpond_uid 发送的用户ID
     * @param boolean $addCount
     */
    function notifyToAtme($uid,$id,$content,$transpond_uid,$addCount=true){
    	$notify['weibo_id'] = $id;
    	$notify['content'] = $content;
    	$arrUids= array();
    	if( $transpond_uid ){
    		array_push($arrUids, $transpond_uid);
    	}
    	$arrUids = array_merge($arrUids, model('User')->getUids($content) );
    	if( $arrUids ){
    		$arrUids = array_unique( $arrUids ); //去重
    		if($addCount){
    			foreach ($arrUids as $v){
    				if(M('user_blacklist')->where("uid=$v AND fid=$uid")->count()==0){
    					$atUids[] = $v;
    				}
    			}
    			model('UserCount')->addCount($atUids,'atme');
    		}
    		model('Atme')->addAtme($arrUids,$id);
    	}
    }
    
    /**
     * 返回一个站内使用的解析微博	
     * @param int $id 微博ID
     * @param array $value
     * @param boolean $api
     * @param int $uid 用户ID
     */
    function getOne($id,$value,$api=false, $uid){
   		return $this->getOneLocation($id, $value, true, $uid);
   	}
   	
    /**
     * 返回一个站内使用的解析微博	
     * @param int $id 微博ID
     * @param array $value
     * @param boolean $show_transpond 显示转发
     * @param int $uid 用户ID
     */
    public function getOneLocation($id, $value, $show_transpond = true, $uid){
    	if (!$value){
    	    $value = $this->where('weibo_id='.$id.' and isdel=0')->find();
    	}
    	if (!$value)
    		return false;
    	$weiboimageConfig = include SITE_PATH . '/apps/weibo/Conf/weiboimageConfig.php';
		if($weiboimageConfig['opennosql'] === "1"){
    		include_once( "./apps/weibo/Lib/Action/PictureAction.class.php" );
    		$pica = new PictureAction();
    		if(intval($value['type']) === 1){
    			$picdata = $pica->getPics($value['weibo_id']);
    			$value['type_data'] = $picdata;
    		}
    	}
        $result = $value;
        $uid = empty($uid) ? $value['uid'] : $uid;
        $value["weibo_id"] = $id;
        $result['is_favorited'] = isset($value['is_favorited']) ? intval($value['is_favorited']) : model('Favorite')->isFavorited($value['weibo_id'], $uid);
        if ($show_transpond && $result['transpond_id']){
        	$result['expend']   = $this->getOne($result['transpond_id']);
        } else {
			if (!$result['expend']) {
        		$result['expend'] = $this->__parseTemplate( $value );
			}
        }
        return $result;
    }
    
    /**
     * 解析模版	
     * @param array $value
     */
    private function __parseTemplate( $value ){
    	static $rand;
    	if ($rand) {
    		$rand++;
    	}else {
    		$rand = time().$value['transpond_id'];
    	}
    	$typedata = unserialize( $value['type_data'] );
		$type     = $value['type'];
		$template = '';
		if($type === "5"){
			$template = A("weibo://Index")->loadbook(array('weibo_id'=>$value['weibo_id'],'typeId'=>$type,'typeData'=>$typedata,'rand'=>$rand));
		}else{
			PluginManager::trigger('weibo_type_parse_tpl',array('weibo_id'=>$value['weibo_id'],'typeId'=>$type,'typeData'=>$typedata,'rand'=>$rand,'result'=>&$template));
		}
		return $template;
    }
    
    /**
     * 缓存微博列表
     * 缓存的key的格式为: weibo_微博ID.
     * @param array $weibo_list 微博ID列表, 或者微博详情列表. 如果为微博ID列表时, 本方法会首先获取微博详情列表, 然后缓存.
     */
    public function setWeiboObjectCache($weibo_list){
        $check_item = $weibo_list{0};
    	if (!is_array($weibo_list))
    		return false;
    	if (!is_array($check_item) && !is_numeric($check_item))
    		return false;
    	if (is_numeric($check_item)) { // 给定的是weibo_id的列表. 查询weibo详情
    	    $weibo_list = array_unique(array_filter($weibo_list));
	    	$map['weibo_id'] = array('in', $weibo_list);
	    	$map['isdel']    = 0;
	    	$weibo_list      = $this->where($map)->select();
    	}
    	foreach ($weibo_list as $v){
    	    $cache = $this->_getWeiboCache($v['weibo_id']);
    	    if(!$cache || empty($cache)){
    	        $this->_setWeiboCache($v['weibo_id'], $v);
    	    }
    	}
	   	return $weibo_list;
    }
    
    /**
     * 获取缓存
     * @param int $id 微博ID
     */
    public function _getWeiboCache($id){
	   return F('weibo_detail_'.$id);
	}

	/**
	 * 删除缓存
	 * @param int $id 微博ID
	 */
	public function _removeWeiboCache($id){
	    return F('weibo_detail_'.$id,NULL);
	}

	/**
	 * 设置缓存	
	 * @param int $id 微博ID
	 * @param array $data
	 */
	public function _setWeiboCache($id,$data){
	    return F('weibo_detail_'.$id,$data);
	}
    
    /**
     * 显示微博	
     * @param int $uid 用户ID
     * @param string $type 类型
     * @param id $since
     * @param int $row 显示条数
     * @param int $gid 分组ID
     */
    function getHomeList($uid, $type='index', $since, $row=10, $gid='') {
    	$row = $row?$row:10;
		if($type=='original'){  //原创
			$map = 'transpond_id=0 AND isdel=0';
    		if($since){
    			$map.=" AND weibo_id<$since";
    		}
    	}else if($type=='index' || $type==''){   // 默认全显
    	    if ($since) {
    			$map="weibo_id < $since AND isdel=0";
    		} else {
    			$map = '1=1 AND isdel=0';
    		}
    	}else {
    		if ($since) {
    			$map="weibo_id < $since AND isdel=0";
    		}else {
    			$map = '1=1 AND isdel=0';
    		}
			$map.=" AND type=".$type;
    	}
        if($uid>0){
			$followCount = model('Follow')->getUserFollowCount($uid);
			if ($followCount) { // 有关注时, 展示关注的用户的微博
				if (is_numeric($gid)) {
					$fids = model('FollowGroup')->getUsersByGroup($uid,$gid);
					$map.=' AND uid IN ('.implode(',',$fids).')';
				}else{
					$map.=" AND ( uid IN (SELECT fid FROM {$this->tablePrefix}weibo_follow WHERE uid=$uid AND type=0) OR uid={$uid})";
				}
			}else{//无关注时.数据为空.
				$map.=' AND uid = '.$uid;
			}
		}
    	$list = $this->where($map)->order('weibo_id DESC')->limit($row)->select();
		unset($map);
        $return['data'] = $this->_paramResultData($list,$uid);
        return $return;
    }
    
    /**
     * 提到我的	
     * @param int $uid 用户ID
     */
    function getAtme($uid,$search) {
    	$count_sql = "SELECT count(*) AS count FROM {$this->tablePrefix}weibo AS w INNER JOIN {$this->tablePrefix}weibo_atme AS a ON w.weibo_id = a.weibo_id
    				  WHERE a.uid = {$uid}
    				  AND a.uid NOT IN ( SELECT b.fid FROM {$this->tablePrefix}user_blacklist AS b WHERE b.uid = {$uid} )";
    	$count = $this->query($count_sql);
    	$count = $count[0]['count'];
    	//查询进行优化
		import("ORG.Util.Page"); // 导入分页类
    	$Page = new Page($count, 10);
    	$data['w.isdel'] = 0;
    	$data['w.uid'] = array('neq',$uid);
    	$data['a.uid'] = $uid;
    	$data['b.fid'] = array('exp','is null');
    	if(!empty($search))
    		$data['w.content'] = array('like','%'.$search.'%');
    	$list = M()->Table("`{$this->tablePrefix}weibo` AS w LEFT JOIN `{$this->tablePrefix}weibo_atme` AS a ON w.weibo_id = a.weibo_id LEFT JOIN `{$this->tablePrefix}user_blacklist` AS b ON w.uid = b.fid AND b.uid = {$uid}")
				   ->field('w.*')
				   ->where($data)
				   ->order('w.ctime DESC')
				   ->select();
	    $return['data'] = $this->_paramResultData($list,$uid);
        return $return;
    }
    
	/**
	 * 我收藏的	
	 * @param int $uid 用户ID
	 */
    function getCollection($uid,$search){
    	$list = M('weibo_favorite')->where("`uid`='{$uid}'")->order('`weibo_id` DESC')->select();
    	$favorite_ids = common('Array')->getSubByKey($list, 'weibo_id');    	
    	$map['weibo_id'] = array('in', $favorite_ids);
    	$map['isdel']	 = '0';
    	if(!empty($search))
    		$map['content'] = array('like','%'.$search.'%');
    	$list['data'] = $this->where($map)->order('`weibo_id` DESC')->limit(count($favorite_ids))->select();
    	//缓存被转发微博的详情, 作者信息, 被转发微博的作者信息
    	$ids = common('Array')->getSubByKeyArray($list['data'], 'weibo_id,transpond_id,uid');
    	$transpond_list = $this->getWeiboDetail($ids['transpond_id']);
    	// 本页的用户IDs = 作者IDs + 被转发微博的作者IDs
    	$ids['uid'] = array_merge($ids['uid'], common('Array')->getSubByKey($transpond_list, 'uid'));
    	model('User')->setUserObjectCache($ids['uid']);
    	foreach( $list['data'] as $key=>$value){
        	$value['is_favorited'] = '1';
 			$list['data'][$key] = $this->getOneLocation($list['data'][$key]['weibo_id'],$value);
        }
        return $list;
    }
    
    /**
     * 搜索	
     * @param string $key 内容
     * @param string $type 类型
     */
    function doSearch($key, $type=''){
    	global $yl;
    	if (!$key) {
    		$list['count'] = 0;
    		return $list;
    	}
    	switch ($type){
    		case '':
    			$list = $this->field('weibo_id')->where("content LIKE '%{$key}%' AND isdel=0" )->order('weibo_id DESC')->findpage(20);
    			break;
    		case 'location':
    			$user = model('User')->where('uid='.$yl['user']['uid'])->field('province')->find();
    			$list = $this->field('weibo_id')->where("uid IN (SELECT uid FROM {$this->tablePrefix}user WHERE province=".$user['province'].") AND content LIKE '%{$key}%' AND isdel=0" )->order('weibo_id DESC')->findpage(20);
    			break;
    		case 'follow':
    			$list = $this->table("{$this->tablePrefix}weibo AS w,(SELECT fid FROM {$this->tablePrefix}weibo_follow WHERE uid={$yl['user']['uid']} AND type=0) AS f")
    						 ->where("w.uid=f.fid AND w.content LIKE '%{$key}%' AND w.isdel=0" )
    						 ->order('weibo_id DESC')
    						 ->field('w.weibo_id as weibo_id')
    						 ->findpage(20);
    			break;
    		case 'original':
    			$list = $this->field('weibo_id')->where("transpond_id=0 AND content LIKE '%{$key}%' AND isdel=0" )->order('weibo_id DESC')->findpage(20);
    			break;
    		case 'image':
    			$list = $this->field('weibo_id')->where("type=1 AND content LIKE '%{$key}%' AND isdel=0" )->order('weibo_id DESC')->findpage(20);
    			break;
    		case 'music':
    			$list = $this->field('weibo_id')->where("type=4 AND content LIKE '%{$key}%' AND isdel=0" )->order('weibo_id DESC')->findpage(20);
    			break;
    		case 'video':
    			$list = $this->field('weibo_id')->where("type=3 AND content LIKE '%{$key}%' AND isdel=0" )->order('weibo_id DESC')->findpage(20);
    			break;
    		case 'file':
    			$list = $this->field('weibo_id')->where("type=5 AND content LIKE '%{$key}%' AND isdel=0" )->order('weibo_id DESC')->findpage(20);
    			break;
    		case 'keyword'://key查询条件直接传进来做查询条件的一部分
    		    $list = $this->field('weibo_id')->where($key." and isdel=0")->order('weibo_id DESC')->findpage(20);
    		    break;
    		default:
    			$list = $this->field('weibo_id')->where("type='{$type}' AND content LIKE '%{$key}%' AND isdel=0" )->order('weibo_id DESC')->findpage(20);
    	}
    	$weibo_id_list = common('Array')->getSubByKey($list['data'],'weibo_id');
    	$list['data'] = $this->getWeiboDetail($weibo_id_list);

    	//缓存用户信息, 被转发微博的详情
    	$ids = common('Array')->getSubByKeyArray($list['data'], 'transpond_id,uid');
    	$transpond_list = $this->getWeiboDetail($ids['transpond_id']);
    	// 本页的用户IDs = 作者IDs + 被转发微博的作者IDs
    	$ids['uid'] = array_merge($ids['uid'], common('Array')->getSubByKey($transpond_list, 'uid'));
    	model('User')->setUserObjectCache($ids['uid']);
    	foreach($list['data'] as $key=>$value){
    		$list['data'][$key] = $this->getOne($value['weibo_id'],$value);
    	}
    	return $list;
    }
    
	/**
	 * 搜索话题	
	 * @param
	 */
    public function doSearchWithTopic($key, $type) {
    	global $yl;
    	if (!$key) {
    		$list['count'] = 0;
    		return $list;
    	}
    	//获取话题ID
    	$topicId = model('Topic')->getTopicId($key);
    	$weiboTopicLinkModel = M('weibo_topic_link');
    	switch ($type){
    		case '':
				$list = $weiboTopicLinkModel->where("topic_id = {$topicId}")->order('weibo_id DESC')->findPage(20);
    			break;
    		case 'original':
				$list = $weiboTopicLinkModel->where("topic_id = {$topicId} AND transpond_id = 0")->order('weibo_id DESC')->findPage(20);
    			break;
    		case 'image':
				$list = $weiboTopicLinkModel->where("topic_id = {$topicId} AND type = '1'")->order('weibo_id DESC')->findPage(20);
    			break;
    		case 'music':
				$list = $weiboTopicLinkModel->where("topic_id = {$topicId} AND type = '4'")->order('weibo_id DESC')->findPage(20);
    			break;
    		case 'video':
				$list = $weiboTopicLinkModel->where("topic_id = {$topicId} AND type = '3'")->order('weibo_id DESC')->findPage(20);
    			break;
    		case 'file':
				$list = $weiboTopicLinkModel->where("topic_id = {$topicId} AND type = '5'")->order('weibo_id DESC')->findPage(20);
    			break;
    		default:
				$list = $weiboTopicLinkModel->where("topic_id = {$topicId} AND type = '{$type}'")->order('weibo_id DESC')->findPage(20);
    	}
		$weiboIdArr = common('Array')->getSubByKey($list['data'], 'weibo_id');
		$listMap['weibo_id'] = array('IN', $weiboIdArr);
		$data = $this->field('weibo_id')->where($listMap)->order('weibo_id DESC')->select();
		$weibo_id_list = common('Array')->getSubByKey($data,'weibo_id');
		$list['data'] = $this->getWeiboDetail($weibo_id_list);
    	//缓存用户信息, 被转发微博的详情
    	$ids = common('Array')->getSubByKeyArray($list['data'], 'transpond_id,uid');
    	$transpond_list = $this->getWeiboDetail($ids['transpond_id']);
    	// 本页的用户IDs = 作者IDs + 被转发微博的作者IDs
    	$ids['uid'] = array_merge($ids['uid'], common('Array')->getSubByKey($transpond_list, 'uid'));
    	model('User')->setUserObjectCache($ids['uid']);
    	foreach($list['data'] as $key=>$value){
    		$list['data'][$key] = $this->getOne($value['weibo_id'],$value);
    	}
    	return $list;
    }

	/**
	 * Topic搜索	
	 * @param
	 */
	function doSearchTopic($map,$order,$uid,$limit = true) {
		if($limit){
		    $list = $this->field('weibo_id')->where($map)->order($order)->findPage(20);
		    $weibo_id_list = common('Array')->getSubByKey($list['data'],'weibo_id');
		    $list['data'] = $this->getWeiboDetail($weibo_id_list);
		}else{
		    $result = $this->field('weibo_id')->where($map)->order($order)->find();
		    $list['data'] = $this->getWeiboDetail($result);
		    if(empty($result)) return false;
		}
		//缓存被转发微博的详情, 作者信息, 被转发微博的作者信息
    	$ids = common('Array')->getSubByKeyArray($list['data'], 'weibo_id,transpond_id,uid');
    	$transpond_list = $this->getWeiboDetail($ids['transpond_id']);
    	// 本页的用户IDs = 作者IDs + 被转发微博的作者IDs
    	$ids['uid'] = array_merge($ids['uid'], common('Array')->getSubByKey($transpond_list, 'uid'));
    	model('User')->setUserObjectCache($ids['uid']);
		$weibo_ids = common('Array')->getSubByKey($list['data'], 'weibo_id');
		foreach($list['data'] as $key=>$value){
			$value['is_favorited'] = model('Favorite')->isFavorited($value['weibo_id'], $uid, $weibo_ids);
			$list['data'][$key] = $this->getOne($value['weibo_id'], $value);
		}
		return $list;
	}
	
	/**
	 * 获取空间微博列表	
	 * @param int $uid 用户ID
	 * @param string $type 微博类型
	 */
	public function getSpaceList($uid, $type) {
    	if ($type == 'original') { // 原创
    		$map = 'transpond_id=0 AND uid='.$uid.' AND isdel=0';
    	} else if ($type == '') { // 默认全显
    		$map = "uid=$uid AND isdel=0";
    	} else {    //其它类型
    		$map = "uid=$uid AND type=".$type.' AND isdel=0';
    	}
        $list = $this->where($map)->order('weibo_id DESC')->findPage(10);
        return $this->_paramResultData($list,$uid,true);
    }
	
	public function _paramResultData($list,$uid,$page=false){
        if($page){
            $data = $list['data'];
        }else{
            $data = $list; 
        }
        $weiboimageConfig = include SITE_PATH . '/apps/weibo/Conf/weiboimageConfig.php';
		if($weiboimageConfig['opennosql'] === "1"){
        	include_once( "./apps/weibo/Lib/Action/PictureAction.class.php" );
        	$pica = new PictureAction();
        	foreach ($data as $k => $v){
        		if(intval($v['type']) === 1){
        			$picdata = $pica->getPics($v['weibo_id']);
        			$data[$k]['type_data'] = $picdata;
        		}
        	}
        }
        //缓存被转发微博的详情, 被转发微博的作者信息
        $ids = common('Array')->getSubByKeyArray($data, 'weibo_id,transpond_id');
        $transpond_list = $this->getWeiboDetail($ids['transpond_id']);
        $ids['uid'] = common('Array')->getSubByKey($transpond_list, 'uid');
        model('User')->setUserObjectCache($ids['uid']);
        $weibo_ids = common('Array')->getSubByKey($data, 'weibo_id');
        foreach( $data as $key=>$value){
            $value['is_favorited'] = model('Favorite')->isFavorited($value['weibo_id'], $uid, $weibo_ids);
            $data[$key] = $this->getOne($value['weibo_id'],$value);
        }
        if($page){
            $list['data'] = $data;
        }else{
            $list = $data;
        }
        return $list;
    }
}